package com.fc.mall.portal.service.impl;

import com.fc.mall.mapper.PmsProductMapper;
import com.fc.mall.mapper.PmsSkuStockMapper;
import com.fc.mall.model.PmsProduct;
import com.fc.mall.model.PmsSkuStock;
import com.fc.mall.model.PmsSkuStockExample;
import com.fc.mall.portal.dto.SkuGroup;
import com.fc.mall.portal.service.SkuStockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class SkuStockServiceImpl implements SkuStockService {

    @Autowired
    private PmsSkuStockMapper skuStockMapper;

    @Autowired
    private PmsProductMapper pmsProductMapper;

    @Override
    public List<PmsSkuStock> getList(Long pid, String keyword) {
        PmsSkuStockExample example = new PmsSkuStockExample();
        PmsSkuStockExample.Criteria criteria = example.createCriteria().andProductIdEqualTo(pid);
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andSkuCodeLike("%" + keyword + "%");
        }
        return skuStockMapper.selectByExample(example);
    }

    @Override
    public List<SkuGroup> getSkuGroupByProduct(Long pid)
    {
        PmsProduct pmsProduct = pmsProductMapper.selectByPrimaryKey(pid);
        List<SkuGroup> skuGroupList = new ArrayList<>();
        Map<String, List<PmsSkuStock>> skuGroupMap = new HashMap<>();
        PmsSkuStockExample example = new PmsSkuStockExample();
        PmsSkuStockExample.Criteria criteria = example.createCriteria().andProductIdEqualTo(pid);
        List<PmsSkuStock> pmsSkuStockList = skuStockMapper.selectByExample(example);
        if (null == pmsSkuStockList && pmsSkuStockList.isEmpty())
        {
            return skuGroupList;
        }
        pmsSkuStockList.forEach( pmsSkuStock -> {
            if(pmsProduct.getPromotionType().intValue() == 1)
            {
                pmsSkuStock.setPromotionPrice(pmsSkuStock.getPrice().multiply(pmsProduct.getPromotionPrice()).divide(new BigDecimal(100)));
            }
            if(skuGroupMap.containsKey(pmsSkuStock.getSp1()))
            {
                skuGroupMap.get(pmsSkuStock.getSp1()).add(pmsSkuStock);
            }
            else
            {
                List<PmsSkuStock> skus = new ArrayList<>();
                skus.add(pmsSkuStock);
                skuGroupMap.put(pmsSkuStock.getSp1(), skus);
            }
        });

        skuGroupMap.keySet().forEach(key ->{
            SkuGroup skuGroup = new SkuGroup(key, skuGroupMap.get(key));
            skuGroupList.add(skuGroup);
        });
        return skuGroupList;
    }
}
